//接受web发送过来的返回事件
window.addEventListener("message", async function (event) {
    //处理页面响应的消息
    if (event.data.from === "web") {
        if (event.data.action == "localStorage_get") {
            await session.set("localStorage", event.data.data);
            // console.log("rev web response: " + JSON.stringify(event.data))
        }
        // console.log("rev web response: " + JSON.stringify(event.data))
    } else {
        // if (!!event.data && !!event.data.from && event.data.from == 'extenstion') {
        //
        // } else {
        //     try {
        //         if (event.data.data.request.api.indexOf("meiri56") == -1) {
        //             console.log(event)
        //         }
        //     } catch (e) {
        //         console.log(event)
        //     }
        // }
    }

});

function webError() {
    if (document.body.innerHTML.indexOf('很抱歉,网站正在维护中') != -1) {
        return true;
    }
    return false;
}

//接受worker.js popup.js
chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    if (request.type == 'heartBeat') {
        let pluginName = await session.get("pluginName", null);
        let hostCode = await session.get("hostCode", null);
        let serverName = await session.get("serverName", null);
        let res = core.heartBeat(pluginName, hostCode, serverName);

        await session.set("heartBeat_time", new Date().getTime())

        let tokenRunning = await session.get("TOKEN_RUNNING", false)
        let stopService = await session.get("stopService", false)
        if (!tokenRunning && !stopService && !webError()) {
            await session.set("TOKEN_RUNNING", true)
            await getAccountAndRefresh();
        }
        sendResponse(res);
    }
    if (request.type == 'reload' || request.type == 'init') {
        if (!webError()) {
            window.location.reload();
        }
    }
    if (request.type == 'getAccount') {
        await getAccountAndRefresh();
        sendResponse("getAccount");
    }
    return true;
});

//current_step = getAccountAndRefresh
async function getAccountAndRefresh() {
    let stopService = await session.get("stopService", false)
    if (stopService) {
        return;
    }
    await session.set("msg", "等待5秒")
    await localTimeFunction(async function () {
        console.log("getAccountAndRefresh: 开始获取账号")
        await session.set("msg", "开始获取账号")
        await session.set("TOKEN_RUNNING", true)
        await session.remove("account");
        await session.remove("loginStatus");
        await session.remove("hasDoneLogin");
        await session.set("current_step", "getAccountAndRefresh");
        await session.set("current_step_time", new Date().getTime());
        let last_account = await session.get("last_account", null)

        let pluginName = await session.get("pluginName", null);
        let hostCode = await session.get("hostCode", null);
        let serverName = await session.get("serverName", null);

        let hasGetAccount = await session.get("hasGetAccount", false);
        let hasGetAccount_time = await session.get("hasGetAccount_time", 0);
        if (!hasGetAccount || new Date().getTime() - hasGetAccount_time > 30000) {
            let res = core.getAccount(pluginName, hostCode, serverName);
            await session.set("hasGetAccount", true);
            await session.set("hasGetAccount_time", new Date().getTime());

            if (!!res && !!res['username']) {
                console.log("getAccountAndRefresh: 账号: " + res['username'])
                await session.set("msg", "获取账号:" + res['username'])
                if (!!last_account && last_account == res['username']) {
                    console.log("getAccountAndRefresh: 与上次账号重复: " + res['username'])
                    await session.set("msg", "与上次账号重复")
                    await localTimeFunction(async function () {
                        await getAccountAndRefresh();
                    }, 2000)
                    return;
                } else {
                    console.log("getAccountAndRefresh: refreshToken " + res['username'])
                    await session.set("msg", "开始设置新账号cookie")
                    await session.set("account", res)

                    await session.set("current_step", "refreshToken");
                    await session.set("current_step_time", new Date().getTime());
                    await session.remove("hasGetAccount");
                }
            } else {
                console.log("getAccountAndRefresh: 未获取到账号")
                await session.set("msg", "未获取到账号")
                await localTimeFunction(async function () {
                    await session.remove("hasGetAccount");
                    await getAccountAndRefresh();
                }, 2000)
            }
        }
    }, 5000)
}

setInterval(async function () {
    let current_step = await session.get("current_step", null);
    let account = await session.get("account", null)
    let done_refreshToken = await session.get("done_refreshToken", false)
    let done_refreshToken_time = await session.get("done_refreshToken_time", 0)
    let stopService = await session.get("stopService", false)
    if (current_step == "refreshToken" && !!account && (!done_refreshToken || new Date().getTime() - done_refreshToken_time > 30000) && !stopService) {
        await session.set("done_refreshToken", true);
        await session.set("done_refreshToken_time", new Date().getTime());
        await refreshToken(account);
    }
    if (webError()) {
        sendMsg({action: 'delCookie', domain: 'freightsmart.oocl.com', data: null})
        localTimeFunction(function () {
            window.location.reload();
        }, 2000)
    }
}, 3000)

//current_step = refreshToken
async function refreshToken(res) {
    let otherCache = (!!res && !!res['otherCache']) ? JSON.parse(res['otherCache']) : null;
    let apiToken = (!!res && !!res['apiToken']) ? JSON.parse(res['apiToken']) : null;
    if (!!otherCache && !!otherCache['cookies'] && !!otherCache['localStorage']
        && !!apiToken && !!apiToken['X-Auth-Token'] && apiToken['X-Auth-Token'].length > 0) {
        //再增加
        let message = {"from": "extenstion", "action": "localStorage_set", data: otherCache['localStorage']};
        window.postMessage(message, "*");
        sendMsg({action: 'setCookie', data: otherCache['cookies']})
        console.log("设置完cookie: " + res['username'])
        await session.set("msg", "重新设置完新账号cookie到浏览器域")

        await localTimeFunction(async function () {
            console.log("刷新: " + res['username'])
            await session.set("current_step", "checkLogin");
            await session.set("current_step_time", new Date().getTime());
            await session.remove("done_refreshToken");
            await session.remove("resetToken")
            window.location.reload();
        }, 5000)

    } else {
        let resetToken = await session.get("resetToken", 0);
        if (new Date().getTime() - resetToken > 60000 * 2) {
            //先删除
            let message = {"from": "extenstion", "action": "localStorage_del"};
            window.postMessage(message, "*");
            sendMsg({action: 'delCookie', domain: 'freightsmart.oocl.com', data: ['token']})

            await session.set("current_step", "refreshToken_tmp");
            await session.set("current_step_time", new Date().getTime());
            await localTimeFunction(async function () {
                await session.set("msg", "删除历史token")
                var time = new Date().getTime();
                let noLoginCookie = {
                    "localStorage": [
                        {
                            "key": "countryCode",
                            "val": "CN"
                        },
                        {
                            "key": "Hm_lvt_51968685d7ecb4f923773e44887be501",
                            "val": (time + 60000 * 60 * 24) + "|" + (time / 1000)
                        }
                    ],
                    "cookies": [
                        {
                            "domain": "exiamfw.home.oocl.com",
                            "hostOnly": true,
                            "httpOnly": true,
                            "name": "AUTH_SESSION_ID_LEGACY",
                            "path": "/auth/realms/oocl-prd/",
                            "sameSite": "unspecified",
                            "secure": true,
                            "session": true,
                            "storeId": "0",
                            "value": "58ffdd69-a32a-4e86-8fee-6019873e76b9.auth-ex-rhsso-20220620123943049-deployment-7c67dfb996-fzc8p"
                        },
                        {
                            "domain": "exiamfw.home.oocl.com",
                            "hostOnly": true,
                            "httpOnly": true,
                            "name": "AUTH_SESSION_ID",
                            "path": "/auth/realms/oocl-prd/",
                            "sameSite": "no_restriction",
                            "secure": true,
                            "session": true,
                            "storeId": "0",
                            "value": "58ffdd69-a32a-4e86-8fee-6019873e76b9.auth-ex-rhsso-20220620123943049-deployment-7c67dfb996-fzc8p"
                        },
                        {
                            "domain": "freightsmart.oocl.com",
                            "expirationDate": (time + 60000 * 60 * 24) / 1000,
                            "hostOnly": true,
                            "httpOnly": false,
                            "name": "cookie_consent",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": false,
                            "storeId": "0",
                            "value": "statistical=2023-06-19T17:19:23.787009"
                        },
                        {
                            "domain": ".freightsmart.oocl.com",
                            "expirationDate": (time + 60000 * 60 * 24) / 1000,
                            "hostOnly": false,
                            "httpOnly": false,
                            "name": "Hm_lvt_51968685d7ecb4f923773e44887be501",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": false,
                            "storeId": "0",
                            "value": (time / 1000) + ""
                        },
                        {
                            "domain": ".freightsmart.oocl.com",
                            "hostOnly": false,
                            "httpOnly": false,
                            "name": "HMACCOUNT",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": true,
                            "storeId": "0",
                            "value": "XXX"
                        },
                        {
                            "domain": "freightsmart.oocl.com",
                            "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".949083",
                            "hostOnly": true,
                            "httpOnly": false,
                            "name": "django_language",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": false,
                            "storeId": "0",
                            "value": "zh-hans"
                        },
                        {
                            "domain": ".freightsmart.oocl.com",
                            "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".413085",
                            "hostOnly": false,
                            "httpOnly": false,
                            "name": "_ga",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": false,
                            "storeId": "0",
                            "value": "GA1.3.527216470.1729072291"
                        },
                        {
                            "domain": ".freightsmart.oocl.com",
                            "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".413085",
                            "hostOnly": false,
                            "httpOnly": false,
                            "name": "_ga_4W2CH9C5X3",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": false,
                            "storeId": "0",
                            "value": "GS1.3.1729072290.1.1.1729072310.0.0.0"
                        },
                        {
                            "domain": ".freightsmart.oocl.com",
                            "hostOnly": false,
                            "httpOnly": false,
                            "name": "Hm_lpvt_51968685d7ecb4f923773e44887be501",
                            "path": "/",
                            "sameSite": "unspecified",
                            "secure": false,
                            "session": true,
                            "storeId": "0",
                            "value": (time / 1000) + ""
                        }
                    ]
                }
                //set 无效cookie等同于删除cookie，cma删除cookie会触发风控
                message = {"from": "extenstion", "action": "localStorage_set", data: noLoginCookie['localStorage']};
                window.postMessage(message, "*");
                sendMsg({action: 'setCookie', data: noLoginCookie['cookies']})

                await localTimeFunction(async function () {
                    await session.set("msg", "历史token清理完毕，刷新")
                    await session.set("current_step", "refreshToken");
                    await session.remove("done_refreshToken");
                    await session.set("resetToken", new Date().getTime())
                    window.location.reload();
                    return;
                }, 2000)

            }, 1000)
        }

        let current_step = await session.get("current_step", null);
        if (current_step != "refreshToken") {
            return;
        }

        var time = new Date().getTime();
        let noLoginCookie = {
            "localStorage": [
                {
                    "key": "countryCode",
                    "val": "CN"
                },
                {
                    "key": "Hm_lvt_51968685d7ecb4f923773e44887be501",
                    "val": (time + 60000 * 60 * 24) + "|" + (time / 1000)
                }
            ],
            "cookies": [
                {
                    "domain": "exiamfw.home.oocl.com",
                    "hostOnly": true,
                    "httpOnly": true,
                    "name": "AUTH_SESSION_ID_LEGACY",
                    "path": "/auth/realms/oocl-prd/",
                    "sameSite": "unspecified",
                    "secure": true,
                    "session": true,
                    "storeId": "0",
                    "value": "58ffdd69-a32a-4e86-8fee-6019873e76b9.auth-ex-rhsso-20220620123943049-deployment-7c67dfb996-fzc8p"
                },
                {
                    "domain": "exiamfw.home.oocl.com",
                    "hostOnly": true,
                    "httpOnly": true,
                    "name": "AUTH_SESSION_ID",
                    "path": "/auth/realms/oocl-prd/",
                    "sameSite": "no_restriction",
                    "secure": true,
                    "session": true,
                    "storeId": "0",
                    "value": "58ffdd69-a32a-4e86-8fee-6019873e76b9.auth-ex-rhsso-20220620123943049-deployment-7c67dfb996-fzc8p"
                },
                {
                    "domain": "freightsmart.oocl.com",
                    "expirationDate": (time + 60000 * 60 * 24) / 1000,
                    "hostOnly": true,
                    "httpOnly": false,
                    "name": "cookie_consent",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": false,
                    "storeId": "0",
                    "value": "statistical=2023-06-19T17:19:23.787009"
                },
                {
                    "domain": ".freightsmart.oocl.com",
                    "expirationDate": (time + 60000 * 60 * 24) / 1000,
                    "hostOnly": false,
                    "httpOnly": false,
                    "name": "Hm_lvt_51968685d7ecb4f923773e44887be501",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": false,
                    "storeId": "0",
                    "value": (time / 1000) + ""
                },
                {
                    "domain": ".freightsmart.oocl.com",
                    "hostOnly": false,
                    "httpOnly": false,
                    "name": "HMACCOUNT",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": true,
                    "storeId": "0",
                    "value": "XXX"
                },
                {
                    "domain": "freightsmart.oocl.com",
                    "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".949083",
                    "hostOnly": true,
                    "httpOnly": false,
                    "name": "django_language",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": false,
                    "storeId": "0",
                    "value": "zh-hans"
                },
                {
                    "domain": ".freightsmart.oocl.com",
                    "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".413085",
                    "hostOnly": false,
                    "httpOnly": false,
                    "name": "_ga",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": false,
                    "storeId": "0",
                    "value": "GA1.3.527216470.1729072291"
                },
                {
                    "domain": ".freightsmart.oocl.com",
                    "expirationDate": (time + 60000 * 60 * 24) / 1000 + ".413085",
                    "hostOnly": false,
                    "httpOnly": false,
                    "name": "_ga_4W2CH9C5X3",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": false,
                    "storeId": "0",
                    "value": "GS1.3.1729072290.1.1.1729072310.0.0.0"
                },
                {
                    "domain": ".freightsmart.oocl.com",
                    "hostOnly": false,
                    "httpOnly": false,
                    "name": "Hm_lpvt_51968685d7ecb4f923773e44887be501",
                    "path": "/",
                    "sameSite": "unspecified",
                    "secure": false,
                    "session": true,
                    "storeId": "0",
                    "value": (time / 1000) + ""
                }
            ]
        }
        //set 无效cookie等同于删除cookie，cma删除cookie会触发风控
        message = {"from": "extenstion", "action": "localStorage_set", data: noLoginCookie['localStorage']};
        window.postMessage(message, "*");
        sendMsg({action: 'setCookie', data: noLoginCookie['cookies']})

        await session.set("msg", "otherCache为空，需要登陆，先删除当前cookie等账号信息")

        await localTimeFunction(async function () {
            console.log("没有othercache，需要登陆")
            await session.set("msg", "删除old cookie完成，准备登陆")
            await session.set("current_step", "login");
            await session.set("current_step_time", new Date().getTime());
            await session.remove("done_refreshToken");
            await session.remove("resetToken")
            window.location.reload();
        }, 5000)
    }
}